package features.advance.jdk.io.unblocking;

import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Set;

/**
 * @author LIN
 * @date 2021-07-12
 */
public class UdpServer {

    public static void main(String[] args) throws Exception{
        DatagramChannel receiveChannel = DatagramChannel.open();

        receiveChannel.configureBlocking(false);

        DatagramSocket socket = receiveChannel.socket();
        socket.bind(new InetSocketAddress(8083));

        Selector selector = Selector.open();

        receiveChannel.register(selector, SelectionKey.OP_READ);

        if(selector.select()>0){
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            for (SelectionKey key : selectionKeys) {
                if(key.isAcceptable()){

                }
                if(key.isReadable()){
                    ByteBuffer buffer = ByteBuffer.allocate(5000);
//                    receiveChannel.receive(buffer);
                    DatagramChannel channel = (DatagramChannel)key.channel();
                    channel.receive(buffer);
                    System.out.println(new String(buffer.array(),0,buffer.position()));

                }
            }
        }

    }

}
